package com.intretech.umsin.swagger;

import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import springfox.documentation.builders.ApiInfoBuilder;
import springfox.documentation.builders.PathSelectors;
import springfox.documentation.builders.RequestHandlerSelectors;
import springfox.documentation.service.ApiKey;
import springfox.documentation.service.AuthorizationScope;
import springfox.documentation.service.Contact;
import springfox.documentation.service.SecurityReference;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.DocExpansion;
import springfox.documentation.swagger.web.UiConfiguration;
import springfox.documentation.swagger.web.UiConfigurationBuilder;
import springfox.documentation.swagger2.annotations.EnableSwagger2;

import java.util.ArrayList;
import java.util.List;

/**
 * @version V1.0
 * @ClassName: SwaggerConfig
 * @Description: SwaggerConfig 服务实现
 * @author: 李启联
 * @date: 2022-04-26 15:57
 * @Copyright: Copyright (c) 2022
 */
@ConditionalOnClass(Docket.class)
@ConditionalOnProperty(prefix = "intretech.umsin.swagger", name = "enabled",havingValue = "true", matchIfMissing = true)
@Configuration
@EnableSwagger2
@EnableConfigurationProperties(SwaggerProperties.class)
public class SwaggerConfig {

    /**
     * swagger接口配置.
     */
    @Bean
    public Docket api(SwaggerProperties p) {
//        Parameter p0 = new ParameterBuilder().name("Set-Cookie").description("JSESSIONID设值，登录成功后传递可以免于安全拦截.")
//                .modelRef(new ModelRef("string"))
//                .parameterType("header")
//                .required(false).build();
//        Parameter p1 = new ParameterBuilder().name("Authorization").description("Token设值，登录成功后传递可以免于安全拦截.")
//                .modelRef(new ModelRef("string"))
//                .parameterType("header")
//                .required(false).build();
//        List<Parameter> parameters = new ArrayList<>();
//        parameters.add(p0);
//        parameters.add(p1);
//
//        return new Docket(DocumentationType.SWAGGER_2)
//                .apiInfo(
//                        new ApiInfoBuilder().title(p.getApiTitle())
//                                .description(p.getApiDescription())
//                                .version(p.getApiVersion())
//                                .contact(new Contact(p.getApiContactName(), p.getApiContactUrl(), p.getApiContactEmail()))
//                                .build()
//                ).select()
//                .apis(Predicates.and(
//                        RequestHandlerSelectors.withClassAnnotation(RestController.class),
//                        RequestHandlerSelectors.basePackage("com.intretech.umsin")
//                ))
//                .paths(PathSelectors.any())
//                .build()
//                .globalOperationParameters(parameters);
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(
                       new ApiInfoBuilder().title(p.getApiTitle())
                                .description(p.getApiDescription())
                                .version(p.getApiVersion())
                                .contact(new Contact(p.getApiContactName(), p.getApiContactUrl(), p.getApiContactEmail()))
                                .build()
                )
                .enable(p.isEnabled()).select()
                //扫描的路径包
                .apis(RequestHandlerSelectors.basePackage(p.getBaseScanPackage()))
                // 指定路径处理PathSelectors.any()代表所有的路径
                .paths(PathSelectors.any()).build()
                .pathMapping("/")
                .securitySchemes(securitySchemes())
                .securityContexts(securityContexts());

    }

    //securitySchemes的ApiKey中增加一个名为“Authorization”，type为“header”的参数
    private List<ApiKey> securitySchemes() {
        List<ApiKey> apiKeyList = new ArrayList();
        apiKeyList.add(new ApiKey("Authorization", "Authorization", "header"));
        return apiKeyList;
    }

    private List<SecurityReference> defaultAuth() {
        AuthorizationScope authorizationScope = new AuthorizationScope("global", "accessEverything");
        AuthorizationScope[] authorizationScopes = new AuthorizationScope[1];
        authorizationScopes[0] = authorizationScope;
        List<SecurityReference> securityReferences = new ArrayList<>();
        securityReferences.add(new SecurityReference("Authorization", authorizationScopes));
        return securityReferences;
    }

    private List<SecurityContext> securityContexts() {
        List<SecurityContext> securityContexts = new ArrayList<>();
        securityContexts.add(
                SecurityContext.builder()
                        .securityReferences(defaultAuth())
                        .forPaths(PathSelectors.regex("^(?!auth).*$"))
                        .build());
        return securityContexts;
    }


    /**
     * 创建UI信息
     *
     * @return ui配置类.
     */
    @Bean
    UiConfiguration uiConfig() {
        return UiConfigurationBuilder.builder()
                .filter(true)
                .docExpansion(DocExpansion.LIST)
                .build();
    }
}
